package com.qiantu.phone.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.View;
import android.view.ViewConfiguration;

import com.qiantu.phone.R;
import com.qiantu.phone.app.AppApplication;

public class ColorDeviceSeekBar extends View {
    private float mTouchDownX;
    private float mTouchDownY;
    private int mScaledTouchSlop;
    private Drawable progressTextBg;
    private Drawable leftIcon;
    private Drawable rightIcon;
    // 画笔
    private Paint mPaint;
    private Paint mThumbPaint;
    // 滑块按钮宽度
    private float mThumbWidth;
    private float mThumbStrokeWidth;
    private float mThumbHeight;
    private float progressTextSize;
    private float textMarginTop;
    private float textMarginBottom;
    private float progressTrackHeight;
    private float leftIconMarginRight;
    private float rightIconMarginLeft;
    private int textHeight;
    private int textHolderHeight;
    private String progressText = null;
    private float progress;
    //步长100的进度值
    private int progressStep100;
    private float canSlideTotalWidth;
    private ColorTemperatureSeekBar.OnSeekBarChangeListener mOnSeekBarChangeListener;
    private boolean isOverTouchSlop;
    private float thumbCx;
    private boolean isOnlyClick = false;
    private long lastDownTime;
    private float slidDistance;
    private boolean isFirst;
    private RectF mBarRectF;
    private int[] gradientColors = new int[] {0xffffb347, 0xffffb347};
    private int leftRightIconWh;
    private int mThumbLeftRightOffset;
    private int minValue = 0;
    private int maxValue = 100;
    private float totalProgress;
    private boolean isOpen = false;
    private int mColorValue;

    public ColorDeviceSeekBar(Context context) {
        this(context, null);
    }

    public ColorDeviceSeekBar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ColorDeviceSeekBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray ta = attrs == null ? null : getContext().obtainStyledAttributes(attrs, R.styleable.ColorTemperatureSeekBar);
        if (ta != null) {
            mThumbWidth = ta.getDimension(R.styleable.ColorTemperatureSeekBar_progress_thumb_width, dp2px(26));
            mThumbHeight = ta.getDimension(R.styleable.ColorTemperatureSeekBar_progress_thumb_height, dp2px(26));
            progressTextSize = ta.getDimension(R.styleable.ColorTemperatureSeekBar_progress_text_size, dp2px(12));
            leftIconMarginRight = ta.getDimension(R.styleable.ColorTemperatureSeekBar_left_icon_margin_right, dp2px(10));
            rightIconMarginLeft = ta.getDimension(R.styleable.ColorTemperatureSeekBar_right_icon_margin_left, dp2px(10));
            leftIcon = ta.getDrawable(R.styleable.ColorTemperatureSeekBar_left_icon);
            rightIcon = ta.getDrawable(R.styleable.ColorTemperatureSeekBar_right_icon);
            progressTextBg = ta.getDrawable(R.styleable.ColorTemperatureSeekBar_progress_text_bg);
            textMarginTop = ta.getDimension(R.styleable.ColorTemperatureSeekBar_progress_text_margin_top, dp2px(8));
            textMarginBottom = ta.getDimension(R.styleable.ColorTemperatureSeekBar_progress_text_margin_bottom, dp2px(0));
            progressTrackHeight = ta.getDimension(R.styleable.ColorTemperatureSeekBar_progress_track_height, dp2px(8));
        }
        mThumbStrokeWidth = dp2px(2);
        mScaledTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
        mBarRectF = new RectF();
        leftRightIconWh = getResources().getDimensionPixelSize(R.dimen.dp_26);
        mThumbLeftRightOffset = getResources().getDimensionPixelSize(R.dimen.dp_5);
        getTotalProgress();
        init();
    }

    private void init() {
        mPaint = new TextPaint();
        mPaint.setAntiAlias(true);

        mThumbPaint = new Paint();
        mThumbPaint.setAntiAlias(true);

        if(progressTextBg != null || progressTextBg.getIntrinsicHeight() == 0){
            textHolderHeight = (int) (progressTextBg.getIntrinsicHeight() + textMarginBottom);
        }else{
            Paint.FontMetrics fontMetrics = mPaint.getFontMetrics();
            textHeight = (int) (fontMetrics.bottom - fontMetrics.top);
            textHolderHeight = (int) (textHeight + textMarginBottom);
        }
    }

    private void getTotalProgress(){
        totalProgress = (maxValue - minValue);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(!isEnabled()){
            return false;
        }
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                lastDownTime = System.currentTimeMillis();
                isFirst = true;
                mTouchDownX = event.getX();
                mTouchDownY = event.getY();
                //高于bar不可操作
                if(event.getY() < textHolderHeight){
                    return false;
                }
                //只有Thumb区域可以点击拖动
                if (mTouchDownX < thumbCx - mThumbWidth / 2f || mTouchDownX > thumbCx + mThumbWidth / 2f) {
                    //圆点之外只能点击
                    isOnlyClick = true;
                } else {
                    //圆点之内可以拖动
                    isOnlyClick = false;
                }
                //已滑动距离
                slidDistance = progress * canSlideTotalWidth;
                //重置, 触摸中不进行ScaledTouchSlop判断
                isOverTouchSlop = false;
                break;
            case MotionEvent.ACTION_MOVE:
                if(!isOpen){
                    return true;
                }
                final float x = event.getX();
                float distance = x - mTouchDownX;
                if (!isOnlyClick) {
                    if(isFirst){
                        isFirst = false;
//                        setAlpha(0.8f);
                        if(mOnSeekBarChangeListener != null){
                            mOnSeekBarChangeListener.onStartTrackingTouch();
                        }
                    }
                    getParent().requestDisallowInterceptTouchEvent(true);
                    isOverTouchSlop = true;
                    progress = (distance + slidDistance) / canSlideTotalWidth;
                    progress = progress < 0 ? 0 : progress;
                    progress = progress >= 0.995 ? 1 : progress;
                    calculateProgressStep100();
                    calculateColorTemp();
                    invalidate();
                    if (mOnSeekBarChangeListener != null) {
                        mOnSeekBarChangeListener.onValueChanged(mColorValue);
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
                //关闭状态不触发
                if(!isOpen){
                    return true;
                }
                //点击
                float upX = event.getX();
                float upY = event.getY();
                float clickDistance = (float) Math.sqrt(Math.pow(Math.abs(upX - mTouchDownX), 2) + Math.pow(Math.abs(upY - mTouchDownY), 2));
                if (clickDistance <= dp2px(2)) {
                    progress = (event.getX() - (leftRightIconWh + leftIconMarginRight - mThumbLeftRightOffset)) / canSlideTotalWidth;
                    progress = progress < 0 ? 0 : progress;
                    progress = progress >= 0.995 ? 1 : progress;
                    calculateProgressStep100();
                    calculateColorTemp();
                    invalidate();
                }
                getParent().requestDisallowInterceptTouchEvent(false);
                if (mOnSeekBarChangeListener != null) {
                    playSoundEffect(SoundEffectConstants.CLICK);
                    mOnSeekBarChangeListener.onStopTrackingTouch(mColorValue);
                }
//                setAlpha(1f);
                break;
            case MotionEvent.ACTION_CANCEL:
                break;
        }
        return true;
    }

    private void calculateColorTemp(){
        mColorValue = progressStep100 + minValue;
        mColorValue = mColorValue < minValue ? minValue : mColorValue;
        mColorValue = mColorValue > maxValue ? maxValue : mColorValue;
    }

    @Override
    protected synchronized void onDraw(Canvas canvas) {
        if(leftIcon != null){
            leftIcon.draw(canvas);
        }
        if(rightIcon != null){
            rightIcon.draw(canvas);
        }
        if (isOpen) {
            mPaint.setColor(AppApplication.getInstance().getThemeColor(R.attr.deviceCloseBgColor));
            canvas.drawRoundRect(mBarRectF, progressTrackHeight, progressTrackHeight, mPaint);

            thumbCx = leftRightIconWh + leftIconMarginRight - mThumbLeftRightOffset + (canSlideTotalWidth * (progressStep100 / totalProgress)) + mThumbWidth / 2f;
            mPaint.setColor(AppApplication.getInstance().getThemeColor(R.attr.secondaryColor2));
            canvas.drawRoundRect(mBarRectF.left,mBarRectF.top, thumbCx,mBarRectF.bottom,progressTrackHeight, progressTrackHeight, mPaint);

            mThumbPaint.setColor(AppApplication.getInstance().getThemeColor(R.attr.secondaryColor4));
            canvas.drawCircle(thumbCx, mBarRectF.top + (progressTrackHeight / 2f), mThumbWidth / 2f, mThumbPaint);
            mThumbPaint.setColor(0xffffffff);
            canvas.drawCircle(thumbCx, mBarRectF.top + (progressTrackHeight / 2f), (mThumbWidth - mThumbStrokeWidth) / 2f, mThumbPaint);

            int progressTextBgLeft = (int) (thumbCx - progressTextBg.getIntrinsicWidth() / 2);
            int progressTextBgRight = (int) (thumbCx + progressTextBg.getIntrinsicWidth() / 2);
            if(progressTextBg != null){
                progressTextBg.setBounds(progressTextBgLeft, 0, progressTextBgRight, progressTextBg.getIntrinsicHeight());
            }
            if(mColorValue != 0){
                progressTextBg.draw(canvas);
                progressText = mColorValue + "";
                mPaint.setTextSize(progressTextSize);
                int textX = (int) (thumbCx - mPaint.measureText(progressText) / 2);
                mPaint.setColor(AppApplication.getInstance().getThemeColor(R.attr.secondaryColor6));
                canvas.drawText(progressText, textX, -mPaint.getFontMetrics().top + textMarginTop, mPaint);
            }
        }else{
            mPaint.setShader(null);
            mPaint.setColor(AppApplication.getInstance().getThemeColor(R.attr.secondaryColor10));
            canvas.drawRoundRect(mBarRectF, progressTrackHeight, progressTrackHeight, mPaint);
        }
    }

    @Override
    protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int dw = getMeasuredWidth();
        int leftRightIconTop = 0;
        if(leftIcon != null){
            leftRightIconTop = (int) (textHolderHeight + (mThumbHeight - leftRightIconWh) / 2f);
            leftIcon.setBounds(0, leftRightIconTop, leftRightIconWh, leftRightIconTop + leftRightIconWh);
        }
        if(rightIcon != null){
            leftRightIconTop = (int) (textHolderHeight + (mThumbHeight - leftRightIconWh) / 2f);
            rightIcon.setBounds(dw - leftRightIconWh, leftRightIconTop, dw, leftRightIconTop + leftRightIconWh);
        }
        int dh = (int) (mThumbHeight + textHolderHeight);
        setMeasuredDimension(dw, dh);
        mBarRectF.left = leftRightIconWh + leftIconMarginRight;
        mBarRectF.right = dw - leftRightIconWh - rightIconMarginLeft;
        mBarRectF.top = textHolderHeight + (mThumbHeight - progressTrackHeight) / 2f;
        mBarRectF.bottom = mBarRectF.top + progressTrackHeight;
        canSlideTotalWidth = mBarRectF.right - mBarRectF.left - (mThumbWidth - mThumbLeftRightOffset * 2);
    }


    public void setColorValue(int colorValue) {
        mColorValue = colorValue;
        progress = (Float.valueOf(mColorValue) - minValue) / (maxValue - minValue);
        progress = progress < 0 ? 0 : progress;
        progress = progress > 1 ? 1 : progress;
        calculateProgressStep100();
        invalidate();
    }

    private void calculateProgressStep100(){
        progressStep100 = (int) Math.ceil(progress * totalProgress);
    }

    public int getColorValue() {
        return mColorValue;
    }

    public void setOpenState(boolean openState) {
        if(isOpen == openState){
            return;
        }
        isOpen = openState;
        invalidate();
    }

    /**
     * 进度监听
     */
    public interface OnSeekBarChangeListener {
        /**
         * 进度监听回调
         *
         * @param progress 进度
         */
        public void onValueChanged(int progress);

        /**
         * 开始拖动
         */
        public void onStartTrackingTouch();

        /**
         * 停止拖动
         */
        public void onStopTrackingTouch(int progress);
    }

    public void setOnSeekBarChangeListener(ColorTemperatureSeekBar.OnSeekBarChangeListener changeListener) {
        this.mOnSeekBarChangeListener = changeListener;
    }

    /**
     * dp转px
     *
     * @param dp dp值
     * @return px值
     */
    public int dp2px(float dp) {
        return (int) (getResources().getDimension(R.dimen.dp_1) * dp);
    }
}
